<template>
  <div class="app-container">
    <el-card class="coupon-group-card">
      <template #header>
        <div class="card-header">
          <span>优惠券组详情</span>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <el-descriptions :column="1" border>
        <!-- <el-descriptions-item label="优惠券组ID">{{ groupInfo.id || 'N/A' }}</el-descriptions-item> -->
        <el-descriptions-item label="优惠券组名称">{{
          groupInfo.name || "N/A"
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="coupon-list-card">
      <template #header>
        <div class="card-header">
          <span>优惠券列表</span>
          <el-button type="primary" @click="handleAddCoupon">新增</el-button>
        </div>
      </template>

      <el-table :data="coupons" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="优惠券名称" width="160" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 0" type="success">满减券</el-tag>
            <el-tag v-else-if="scope.row.type === 1" type="primary"
              >折扣券</el-tag
            >
            <span v-else>未知类型</span>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="优惠值" width="100">
          <template #default="scope">
            <span v-if="scope.row.type === 0">$</span>{{ scope.row.value || 0 }}
            <span v-if="scope.row.type === 1">{{ scope.row.value || 0 }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="info">未使用</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success"
              >已使用</el-tag
            >
            <el-tag v-else-if="scope.row.status === 2" type="danger"
              >已过期</el-tag
            >
            <span v-else>未知状态</span>
          </template>
        </el-table-column>
        <el-table-column prop="minAmount" label="使用门槛" width="100">
          <template #default="scope">
            ${{ scope.row.minAmount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="couponStock" label="库存" width="80">
          <template #default="scope">
            {{ scope.row.couponStock || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          label="开始时间"
          align="center"
          prop="startTime"
          width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="结束时间"
          align="center"
          prop="endTime"
          width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" /> -->
        <!-- <el-table-column label="关联商品" width="200">
          <template #default="scope">
            <div class="sku-action-container">
              <template v-if="scope.row.skus && scope.row.skus.length > 0">
                <el-button
                  type="primary"
                  link
                  @click="showAllSkus(scope.row.skus)"
                  class="sku-count-button">
                  查看 {{ scope.row.skus.length }} 个关联商品
                </el-button>
              </template>
              <div v-else class="no-sku">
                <span class="no-sku-text">无关联商品</span>
              </div>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="操作">
          <!--按钮在一排里面-->
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)">
              详情
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDeleteCoupon(scope.row)"
              :disabled="scope.row.status === 1">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loading && coupons.length === 0" class="no-data">
        暂无优惠券数据
      </div>
    </el-card>

    <!-- 商品详情弹窗 -->
    <el-dialog
      v-model="skuDialogVisible"
      :title="'关联商品 (' + currentSkus.length + ')'"
      width="800px"
      append-to-body>
      <el-table :data="currentSkus" height="400">
        <el-table-column prop="code" label="SKU编码" width="180">
          <template #default="scope">
            <span class="sku-code">{{ scope.row.code || "无编码" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="skuName" label="商品名称">
          <template #default="scope">
            <div class="sku-name-cell">
              <span class="sku-name">{{
                scope.row.skuName || "未知商品"
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="当前价格" width="100">
          <template #default="scope">
            <span class="current-price">${{ scope.row.price || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100">
          <template #default="scope">
            <span class="original-price" v-if="scope.row.originalPrice"
              >${{ scope.row.originalPrice }}</span
            >
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80">
          <template #default="scope">
            <span>{{ scope.row.stock || 0 }}</span>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="skuDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增优惠券弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增优惠券"
      width="600px"
      append-to-body>
      <el-form
        ref="addCouponFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>

        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择优惠券类型">
            <el-option label="满减券" :value="0" />
            <el-option label="折扣券" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="优惠值" prop="value">
          <el-input-number
            v-model="addForm.value"
            :min="0"
            controls-position="right"
            style="width: 100%"
            :precision="addForm.type === 1 ? 0 : 2" />
          <div class="form-tip">
            {{
              addForm.type === 1
                ? "折扣券：输入1-100之间的整数"
                : "满减券：输入减免金额"
            }}
          </div>
        </el-form-item>

        <el-form-item label="使用门槛" prop="minAmount">
          <el-input-number
            v-model="addForm.minAmount"
            :min="0"
            controls-position="right"
            style="width: 100%" />
          <div class="form-tip">订单满多少金额可使用</div>
        </el-form-item>

        <el-form-item label="库存数量" prop="couponStock">
          <el-input-number
            v-model="addForm.couponStock"
            :min="1"
            controls-position="right"
            style="width: 100%" />
        </el-form-item>

        <el-form-item label="有效期" prop="timeRange">
          <el-date-picker
            v-model="addForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CouponGroupDetail">
import { ref, onMounted, nextTick, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getGroup } from "@/api/market/coupon";
import {
  getCouponsByGroupId,
  createCoupon,
  deleteCoupon,
} from "@/api/market/coupon";
import { parseTime } from "@/utils/ruoyi";

const route = useRoute();
const router = useRouter();

const groupInfo = ref({});
const coupons = ref([]);
const loading = ref(true);

// 商品弹窗相关
const skuDialogVisible = ref(false);
const currentSkus = ref([]);

// 新增优惠券弹窗相关
const addDialogVisible = ref(false);
const addCouponFormRef = ref(null);

// 新增优惠券表单数据
const addForm = reactive({
  name: "",
  type: 0,
  value: 0,
  minAmount: 0,
  couponStock: 0,
  timeRange: [],
});

// 表单验证规则
const addRules = {
  name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择优惠券类型", trigger: "change" }],
  value: [{ required: true, message: "请输入优惠值", trigger: "blur" }],
  minAmount: [{ required: true, message: "请输入使用门槛", trigger: "blur" }],
  couponStock: [{ required: true, message: "请输入库存数量", trigger: "blur" }],
  timeRange: [{ required: true, message: "请选择有效期", trigger: "change" }],
};

// 获取优惠券组详情和优惠券列表
async function fetchCouponGroupDetail() {
  const groupId = route.params.id;
  if (!groupId) {
    goBack();
    return;
  }

  try {
    // 获取优惠券组信息
    const groupResponse = await getGroup(groupId);
    groupInfo.value = groupResponse.data || {};

    // 获取该组下的优惠券
    loading.value = true;
    const couponResponse = await getCouponsByGroupId(groupId);
    coupons.value = Array.isArray(couponResponse.data)
      ? couponResponse.data
      : [];
  } catch (error) {
    console.error("获取优惠券组详情失败:", error);
    groupInfo.value = {};
    coupons.value = [];
  } finally {
    loading.value = false;
  }
}

// 显示所有商品
function showAllSkus(skus) {
  currentSkus.value = skus;
  skuDialogVisible.value = true;
}

// 处理新增优惠券
function handleAddCoupon() {
  // 重置表单
  addForm.name = "";
  addForm.type = 0;
  addForm.value = 0;
  addForm.minAmount = 0;
  addForm.couponStock = 0;
  addForm.timeRange = [];

  addDialogVisible.value = true;
}

// 提交新增表单
function submitAddForm() {
  addCouponFormRef.value.validate(async (valid) => {
    if (valid) {
      const groupId = route.params.id;
      const requestData = {
        name: addForm.name,
        type: addForm.type,
        value: addForm.value,
        minAmount: addForm.minAmount,
        couponStock: addForm.couponStock,
        startTime: addForm.timeRange[0],
        endTime: addForm.timeRange[1],
        couponGroupId: groupId,
      };

      try {
        const response = await createCoupon(requestData);
        if (response.code === 200) {
          // 关闭弹窗
          addDialogVisible.value = false;

          // 重新加载优惠券列表
          fetchCouponGroupDetail();

          // 提示成功
          ElMessage.success("优惠券创建成功");
        } else {
          ElMessage.error(response.msg || "创建失败");
        }
      } catch (error) {
        console.error("创建优惠券失败:", error);
        ElMessage.error("创建优惠券失败");
      }
    }
  });
}

// 处理删除优惠券
function handleDeleteCoupon(row) {
  ElMessageBox.confirm(
    `确认要删除优惠券"${row.name}"吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const response = await deleteCoupon(row.id);
        if (response.code === 200) {
          // 重新加载优惠券列表
          fetchCouponGroupDetail();

          // 提示成功
          ElMessage.success("优惠券删除成功");
        } else {
          ElMessage.error(response.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除优惠券失败:", error);
        ElMessage.error("删除优惠券失败");
      }
    })
    .catch(() => {
      // 用户取消删除
      ElMessage.info("已取消删除");
    });
}
// 处理详情优惠券
function handleDetail(row) {
  router.push({
    path: `/market/coupon/couponDetail/${row.id}`,
  });
}

// 返回上一页
function goBack() {
  router.go(-1);
}

onMounted(() => {
  nextTick(() => {
    fetchCouponGroupDetail();
  });
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-group-card {
  margin-bottom: 20px;
}

.sku-action-container {
  display: flex;
  align-items: center;
  height: 100%;
}

.sku-count-button {
  padding: 0;
}

.no-sku {
  display: flex;
  align-items: center;
  height: 100%;
}

.no-sku-text {
  font-size: 12px;
  color: #999;
}

.sku-name-cell {
  display: flex;
  align-items: center;
}

.sku-image-mini,
.sku-image-placeholder {
  width: 40px;
  height: 40px;
  margin-right: 10px;
  flex-shrink: 0;
}

.sku-image-mini {
  object-fit: cover;
  border-radius: 4px;
}

.sku-image-placeholder {
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  border-radius: 4px;
}

.sku-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sku-code {
  font-family: monospace;
}

.current-price {
  color: #ff4d4f;
  font-weight: 500;
}

.original-price {
  color: #999;
  text-decoration: line-through;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #999;
}

.dialog-footer {
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
